package com.imooc.service.impl;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.imooc.enums.CommentLevel;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.*;
import com.imooc.pojo.*;
import com.imooc.pojo.vo.CommentLevelCountsVO;
import com.imooc.pojo.vo.ItemCommentVO;
import com.imooc.pojo.vo.SearchItemsVO;
import com.imooc.pojo.vo.ShopcartVO;
import com.imooc.service.ItemService;
import com.imooc.service.base.BaseService;
import com.imooc.utils.DesensitizationUtil;
import com.imooc.utils.PagedGridResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @author Administrator
 */
@Service
public class ItemServiceImpl extends BaseService implements ItemService {

    @Autowired
    private ItemsMapper itemsMapper;

    @Autowired
    private ItemsSpecMapper itemsSpecMapper;

    @Autowired
    private ItemsParamMapper itemsParamMapper;

    @Autowired
    private ItemsImgMapper itemsImgMapper;

    @Autowired
    private ItemsCommentsMapper itemsCommentsMapper;

    @Autowired
    private ItemsCustomMapper itemsCustomMapper;

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public Items getById(String itemId) {
        return this.itemsMapper.selectByPrimaryKey(itemId);
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public ItemsParam getByItemId(String itemId) {
        Example example = new Example(ItemsParam.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        return itemsParamMapper.selectOneByExample(example);
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public List<ItemsSpec> getItemsSpecsByItemId(String itemId) {
        Example example = new Example(ItemsSpec.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        return itemsSpecMapper.selectByExample(example);
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public List<ItemsImg> getItemsImgListByItemId(String itemId) {
        Example example = new Example(ItemsSpec.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        return itemsImgMapper.selectByExample(example);
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public CommentLevelCountsVO getCommentCount(String itemId) {
        Integer goodComment = this.getComment(itemId, CommentLevel.GOOD.type);
        Integer normalComment = this.getComment(itemId, CommentLevel.NORMAL.type);
        Integer dadComment = this.getComment(itemId, CommentLevel.BAD.type);
        Integer totalCounts = goodComment + normalComment + dadComment;
        CommentLevelCountsVO commentLevelCountsVO = new CommentLevelCountsVO();
        commentLevelCountsVO.setTotalCounts(totalCounts);
        commentLevelCountsVO.setGoodCounts(goodComment);
        commentLevelCountsVO.setNormalCounts(normalComment);
        commentLevelCountsVO.setBadCounts(dadComment);
        return commentLevelCountsVO;
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public PagedGridResult listPageItemsComments(String itemsId, Integer commentLevel, Integer page, Integer pageSize) {
        // 构造分页传递参数
        Map<String, Object> conditionMap = Maps.newHashMap();
        conditionMap.put("itemsId", itemsId);
        conditionMap.put("commentLevel", commentLevel);
        List<ItemCommentVO> vos = itemsCustomMapper.listPageItemsComments(conditionMap);
        // 个人昵称脱敏
        for (ItemCommentVO itemCommentVO : vos) {
            itemCommentVO.setNickname(DesensitizationUtil.commonDisplay(itemCommentVO.getNickname()));
        }
        PageHelper.startPage(page, pageSize);
        return setterPagedGrid(vos, page);
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public PagedGridResult searchListPageItems(String keywords, String sort, Integer page, Integer pageSize) {
        // 构造分页传递参数
        Map<String, Object> conditionMap = Maps.newHashMap();
        conditionMap.put("keywords", keywords);
        conditionMap.put("sort", sort);
        List<SearchItemsVO> vos = itemsCustomMapper.searchListPageItems(conditionMap);
        PageHelper.startPage(page, pageSize);
        return setterPagedGrid(vos, page);
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public PagedGridResult searchListPageByCatId(Integer catId, String sort, Integer page, Integer pageSize) {
        // 构造分页传递参数
        Map<String, Object> conditionMap = Maps.newHashMap();
        conditionMap.put("catId", catId);
        conditionMap.put("sort", sort);
        List<SearchItemsVO> vos = itemsCustomMapper.searchListPageByCatId(conditionMap);
        PageHelper.startPage(page, pageSize);
        return setterPagedGrid(vos, page);
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public List<ShopcartVO> queryItemsBySpecIds(String specIds) {
        // 获取从前端传递的规格ids并进行对购物车渲染数据
        String[] ids = specIds.split(",");
        List<String> specIdsList = new ArrayList<>();
        Collections.addAll(specIdsList, ids);
        return itemsCustomMapper.queryItemsBySpecIds(specIdsList);
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public ItemsSpec getItemsSpecsBySpecId(String specId) {
        return this.itemsSpecMapper.selectByPrimaryKey(specId);
    }

    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public String queryItemMainImgById(String itemId) {
        ItemsImg itemsImg = new ItemsImg();
        itemsImg.setItemId(itemId);
        itemsImg.setIsMain(YesOrNo.YES.type);
        return this.itemsImgMapper.selectOne(itemsImg).getUrl();
    }

    @Override
    public void decreaseItemSpecStock(String specId, Integer buyCounts) {
        int result = itemsCustomMapper.decreaseItemSpecStock(specId, buyCounts);
        if (result != 1) {
            throw new RuntimeException("订单创建失败，原因：库存不足!");
        }
    }

    //************************************************** 私有方法 ****************************************************//

    /**
     * 获取评论数
     */
    private Integer getComment(String itemId, Integer level) {
        ItemsComments itemsComments = new ItemsComments();
        itemsComments.setItemId(itemId);
        if (Objects.isNull(itemId)) {
            return 0;
        }
        itemsComments.setCommentLevel(level);
        return this.itemsCommentsMapper.selectCount(itemsComments);

    }

}
